﻿/************************************************************************

   Extended Silverlight Toolkit

   Copyright (C) 2010-2012 Xceed Software Inc.

   This program is provided to you under the terms of the Microsoft Public
   License (Ms-PL) as published at http://extendedsilverlight.codeplex.com/license

   Please purchase a commercial version of this toolkit if you are using
   it in a commercial product. The commercial versions support the project,
   and also include more features for each control, priority support,
   source code, updates, removed watermark, and a proprietary license.

   Visit http://xceed.com and follow @datagrid on Twitter.

  **********************************************************************/

using System;
using System.Collections.Generic;

namespace Xceed.Silverlight.Data.Stats
{
  public class MedianFunction : StatFunction
  {
    public MedianFunction()
      : base()
    {
    }

    public MedianFunction( string resultPropertyName, string sourcePropertyName )
      : base( resultPropertyName, sourcePropertyName )
    {
    }

    protected internal override void Validate()
    {
      base.Validate();
      this.ValidateSourcePropertyName( 1 );
    }

    protected override void Initialize( Type[] sourcePropertyTypes )
    {
      base.Initialize( sourcePropertyTypes );

      switch( Type.GetTypeCode( sourcePropertyTypes[ 0 ] ) )
      {
        case TypeCode.Char:
        case TypeCode.Byte:
        case TypeCode.SByte:
        case TypeCode.Int16:
        case TypeCode.Int32:
        case TypeCode.Int64:
        case TypeCode.UInt16:
        case TypeCode.UInt32:
        case TypeCode.UInt64:
        case TypeCode.Single:
        case TypeCode.Double:
          m_resultType = TypeCode.Double;
          break;

        case TypeCode.Decimal:
          m_resultType = TypeCode.Decimal;
          break;
      }
    }

    protected internal override void Reset()
    {
      m_values.Clear();
    }

    protected internal override void Accumulate( object[] values )
    {
      if( StatFunction.CanProcessValues( values, 1 ) )
      {
        checked
        {
          this.AddValueSorted( values[ 0 ] );
        }
      }
    }

    protected internal override StatResult GetResult()
    {
      int count = m_values.Count;
      object result = null;

      if( count > 0 )
      {
        if( count % 2 == 0 )
        {
          // Return the arithmetic mean of the two median numbers.
          checked
          {
            switch( m_resultType )
            {
              case TypeCode.Double:
                {
                  double number1 = Convert.ToDouble( m_values[ count / 2 - 1 ] );
                  double number2 = Convert.ToDouble( m_values[ count / 2 ] );
                  result = ( number1 + number2 ) / 2;
                }
                break;

              case TypeCode.Decimal:
                {
                  Decimal number1 = Convert.ToDecimal( m_values[ count / 2 - 1 ] );
                  Decimal number2 = Convert.ToDecimal( m_values[ count / 2 ] );
                  result = ( number1 + number2 ) / 2;
                }
                break;
            }
          }
        }
        else
        {
          // Return the median number.
          result = m_values[ count / 2 ];
        }
      }

      return new StatResult( result );
    }

    private void AddValueSorted( object value )
    {
      IComparable compValue = value as IComparable;

      if( compValue == null )
        throw new InvalidValueException( "The value is not of a supported numerical type." );

      int start = 0;
      int end = m_values.Count - 1;
      int index;
      int compare;

      while( start <= end )
      {
        index = ( start + end ) / 2;
        compare = compValue.CompareTo( m_values[ index ] );

        if( compare > 0 )
        {
          start = index + 1;
        }
        else if( compare < 0 )
        {
          end = index - 1;
        }
        else
        {
          start = index;
          end = index - 1;
        }
      }

      if( ( start < m_values.Count ) && ( compValue.CompareTo( m_values[ start ] ) > 0 ) )
        start++;

      m_values.Insert( start, value );
    }

    private TypeCode m_resultType = TypeCode.Empty;
    private List<object> m_values = new List<object>();
  }
}
